<template>
    <div class='shopcar'>
        <van-checkbox-group v-model="result" ref="checkboxGroup">
            <van-swipe-cell v-for="item in $store.state.shopadd" :key="item.cid">
                <van-row type="flex">
                    <van-col span="4">
                        <!-- 复选框 -->
                        <van-checkbox :name="item" @click="box"></van-checkbox>
                    </van-col>
                    <van-col span="20">
                        <!-- 商品卡片 -->
                        <van-card :num="item.num" :price="item.price*item.num" :title="item.title" :thumb="item.img" >
                            <template #footer>
                                <van-stepper v-model="item.num" @change="changenum" />
                            </template>
                        </van-card>
                    </van-col>
                </van-row>
                <template #right>
                    <!-- 插槽删除 -->
                    <van-button square text="删除" type="danger" class="delete-button" @click="del(item)" />
                </template>
            </van-swipe-cell>
        </van-checkbox-group>

        <van-submit-bar :price="sum*100" button-text="提交订单">
            <!-- 全选 -->
            <van-checkbox v-model="checked" @click="all">全选</van-checkbox>
        </van-submit-bar>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                result: [],
                checked:false,
            };
        },
        mounted() {},
        methods: {
            // 删除购物车里的数据
            del(item) {
                this.$store.commit("del", item)
                this.result.forEach((res,index)=>{
                    if(res.cid==item.cid){
                        this.result.splice(index,1)
                    }
                });
                this.box()
            },
            // 单选
            box(){
                if(this.result.length == this.$store.state.shopadd.length&&this.$store.state.shopadd.length!=0){
                    this.checked=true;

                }else{
                    this.checked = false
                }
            },
            // 反选
            all(){
                this.$refs.checkboxGroup.toggleAll(this.checked)
            },
            // 将步进器change点击事件传到vuex里
            changenum(){
                this.$store.commit("num")
            }
        },
        computed:{
            sum(){
                // 价格
                let price = 0
                this.result.forEach((item)=>{
                  price+=item.price*item.num  
                });
                return price
            }
        }
    };
</script>

<style lang='scss'>
    .delete-button {
        height: 100%;
    }
    .van-checkbox{
        justify-content: center;
    }
    .van-row--flex{
        align-items: center;
    }
</style>